//
//  LoggerExample.swift
//  SwiftCode
//
//  Created by 于虎拴 on 2022/11/17.
//

import Foundation
import GCDWebServer

class LoggerExample: ListViewController {
  override func getItemCount() -> Int {
    data.count
  }
  
  override func getItem(_ indexPath: IndexPath) -> Item {
    data[indexPath.row]
  }
  
  private lazy var data: [Item] = [
    .init(title: "Timber", description: "打印日期，数组", action: timber),
    // pod "GCDWebServer", "~> 3.0"
    .init(title: "GCDWebServer", description: "GCDWebServer 初始化", action: { [weak self] in
      self?.initWebServer()
    }),
    .init(title: "GCDWebServer", description: "GCDWebServer 启动", action: { [weak self] in
      self?.startWebServer()
    }),
    .init(title: "GCDWebServer", description: "GCDWebServer 关闭", action: { [weak self] in
      self?.stopWebServer()
    }),
  ]
  
  private var gcdWebServer: GCDWebServer?
  
  private func initWebServer() {
    gcdWebServer = GCDWebServer()
    guard let gcdWebServer else { return }
    gcdWebServer.addDefaultHandler(forMethod: "GET", request: GCDWebServerRequest.self) { request in
      return GCDWebServerDataResponse(html: "<html><body><p>Hello World Yuhus</p></body></html>")
    }
  }
  
  private func startWebServer() {
    guard let gcdWebServer else { return }
    gcdWebServer.start(withPort: 8080, bonjourName: "GCD Web Server")
    
    if let serverURL = gcdWebServer.serverURL {
      print("Visit: \(serverURL)")
    }
  }
  
  private func stopWebServer() {
    guard let gcdWebServer else { return }
    gcdWebServer.stop()
  }
}

private func timber() {
  Timber.d(1, "String", Date())
  Timber.e("array:", [1,2,3,4,5,])
}
